<!-- Author: Moe Kyaw Thu Aung --> 
<!-- Last Modified: 11 Sep 2012 --> 
<!-- This handles all db actions of the selling book function and order function --> 
<?php
session_start();

include("confs/config.php");

$action = $_GET['do'];

switch($action) {
	case "add_to_cart":
		add_to_cart();
	break;
	case "clear_cart":
		clear_cart();
	break;
	case "remove_item_from_cart":
		remove_item_from_cart();
	break;
	case "update_cart":
		update_cart();
	break;
	case "order":
		order_now();
	break;
	default: 
		//
}

function add_to_cart() {
	global $DB_NAME, $DB_HOST, $DB_USER, $DB_PASSWORD;
	
	$conn = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD);
	mysql_select_db($DB_NAME, $conn);
	
	$id = $_GET['id'];
	$result = mysql_query("SELECT * FROM items WHERE id = $id");
	$row = mysql_fetch_assoc($result);
	$quantity = $row['qty'];
	$temp = $_SESSION['cart'][$id];
	
	if($quantity > $temp) {
		$_SESSION['cart'][$id]++;
	} else {
		$_SESSION['nomore'] = true;
	}

	header("location: shopping.php");
}

function clear_cart() {
	unset($_SESSION['cart']);
	header("location: shopping.php");
}

function remove_item_from_cart() {
	$id = $_GET['id'];
	
	unset($_SESSION['cart'][$id]);
	
	header("location: view_cart.php");
}

function update_cart() {
	if(count($_POST) > 0) {
		foreach($_POST as $id => $qty) {
			if($qty > 0)
				$_SESSION['cart'][$id] = $qty;
		}
	}
	header("location: view_cart.php");
}

function order_now() {
	global $DB_NAME, $DB_HOST, $DB_USER, $DB_PASSWORD;
	
	$conn = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD);
	mysql_select_db($DB_NAME, $conn);
	
	$name = $_POST['name'];
	$email = $_POST['email'];
	$phone = $_POST['phone'];
	$address = $_POST['address'];
	
	mysql_query("INSERT INTO orders (name, email, phone, address) VALUES ('$name', '$email', '$phone', '$address')");
	
	$order_id = mysql_insert_id($conn);
	
	foreach($_SESSION['cart'] as $item_id => $qty) {
		mysql_query("INSERT INTO order_items (order_id, item_id, qty) VALUES ($order_id, $item_id, $qty)");
		$result = mysql_query("SELECT * FROM items WHERE id = $item_id");
	$quantity = mysql_fetch_assoc($result);
	$newqty = (int)$quantity['qty'] - (int)$qty;
		mysql_query("UPDATE items set qty = $newqty WHERE id = $item_id");
	
	}
	
	$_SESSION['msg'] = "Your order has been sent. The books will be arrive very soon. For additional information, you may contact to 01-123456.";
	unset($_SESSION['cart']);
	$_SESSION['order'] = true;
	header("location: shopping.php");
}
?>
